package com.wngbms.netty.gatewaydemo.filter;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;

public class AddRequestParamFilter implements HttpRequestFilter {

    private String key;
    private String value;
    private HttpRequestFilter nextFilter;

    public AddRequestParamFilter() {
    }

    public AddRequestParamFilter(String key, String value) {
        this.key = key;
        this.value = value;
    }

    public AddRequestParamFilter(HttpRequestFilter nextFilter) {
        this.nextFilter = nextFilter;
    }

    @Override
    public void filter(FullHttpRequest fullHttpRequest, ChannelHandlerContext ctx) {
        String uri = fullHttpRequest.uri();

        int i = uri.indexOf("?");
        String param;
        if (i > 0) {
            param = "&" + key + "=" + value;
        } else {
            param = "?" + key + "=" + value;
        }
        uri = uri + param;
        fullHttpRequest.setUri(uri);

        if (nextFilter != null) {
            nextFilter.filter(fullHttpRequest, ctx);
        }
    }

    public void setNextFilter(HttpRequestFilter nextFilter) {
        this.nextFilter = nextFilter;
    }
}
